package de.tum.in.eist.poll.server;

import java.util.Date;
import java.util.List;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import de.tum.in.eist.poll.client.PollService;
import de.tum.in.eist.poll.shared.Poll;
import de.tum.in.eist.poll.shared.Result;
import de.tum.in.eist.poll.shared.Student;
import de.tum.in.eist.poll.shared.exceptions.PollNotFoundException;
import de.tum.in.eist.poll.shared.exceptions.UserNotFoundException;

@SuppressWarnings("serial")
public class PollServiceImpl extends RemoteServiceServlet implements
		PollService {

	/**
	 * 
	 * Submits the user's input to the database
	 * 
	 * @param pollResult
	 *            representing the user's feedback
	 * @param student
	 *            the submitting student
	 * 
	 * @throws IllegalArgumentException
	 *             if the poll is already closed or the feedback data is wrong
	 *             or the feedback was already submitted
	 * @throws UserNotFoundException
	 *             if the student does not exist in the database
	 * @throws PollNotFoundException
	 *             if the poll does not exist in the database
	 * 
	 * 
	 */

	@Override
	public void submitPoll(Result pollResult, Student student)
			throws IllegalArgumentException, UserNotFoundException,
			PollNotFoundException {
		student = Database.updateUser(student);
		if (student.getSubmittedPolls().contains(pollResult.getDateOfLecture())) {
			throw new IllegalArgumentException("Poll already submitted");
		}
		Poll poll = Database.pollDatabase
				.getPoll(pollResult.getDateOfLecture());
		Date end = poll.getEnd();
		if (new Date().after(end)) {
			throw new IllegalArgumentException("Poll already closed");
		}
		if (pollResult.getQuestion1() > 2 || pollResult.getQuestion1() < -2) {
			throw new IllegalArgumentException("Result out of range");
		}

		Database.pollDatabase.addResult(pollResult);
		student.addSubmittedPoll(poll);
		student.removeAvailablePoll(poll);
		Database.userDatabase.updateUser(student);
	}

	/**
	 * Returns all polls in the database
	 * 
	 * @return list of polls
	 * 
	 */

	@Override
	public List<Poll> getPolls() {
		return Database.pollDatabase.getAllPolls();
	}

	/**
	 * Returns all open polls in the database
	 * 
	 * @return list of polls
	 * 
	 */

	@Override
	public List<Poll> getOpenPolls() {
		return Database.pollDatabase.getOpenPolls();
	}

	/**
	 * Returns all closed polls in the database
	 * 
	 * @return list of polls
	 * 
	 */

	@Override
	public List<Poll> getClosedPolls() {
		return Database.pollDatabase.getClosedPolls();
	}
}
